package com.yankaizhang.blog.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yankaizhang.blog.entity.Article;
import com.yankaizhang.blog.entity.Log;
import com.yankaizhang.blog.service.ArticleService;
import com.yankaizhang.blog.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    ArticleService articleService;

    @Autowired
    LogService logService;


    @RequestMapping({"", "/", "/index"})
    public String adminIndex(Model model){
        addPageInfo(model, "总览");
        List<Log> logs = logService.getLatestLogs();
        Integer articleCount = articleService.getArticleCount();
        Integer totalViews = articleService.getTotalViews();
        model.addAttribute("totalViews", totalViews==null?0:totalViews);
        model.addAttribute("articleCount", articleCount==null?0:articleCount);
        model.addAttribute("logs", logs);
        return "admin/index";
    }

    @RequestMapping("/editor")
    public String editor(Model model){
        addPageInfo(model, "MarkDown编辑器");
        return "admin/editor";
    }

    /**
     * 获取文章列表
     */
    @RequestMapping("/article")
    public String list(Model model,
                       @RequestParam(value = "page", defaultValue = "1") int page,
                       @RequestParam(value = "size", defaultValue = "20") int size){
        PageHelper.startPage(page, size);

        List<Article> list = articleService.list();
        PageInfo<Article> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("link", "/admin/article");
        addPageInfo(model, "文章管理");
        return "admin/article";
    }


    private void addPageInfo(Model model, String title){
        model.addAttribute("title", title);
    }
}
